package ControlLayer;
import java.util.*;
import ModelLayer.*;

/**
 * Write a description of class LoanCtr here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class LoanCtr
{
    // instance variables - replace the example below with your own
    private LoanList lList;
    private static LoanCtr loanCtr;
    private AddressCtr addrCtr;
    private DVDCtr dvdCtr;

    /**
     * Constructor for objects of class LoanCtr
     */
    public LoanCtr()
    {
        //Constructor.
        lList = new LoanList();
        addrCtr= AddressCtr.getInstance();
        dvdCtr= DVDCtr.getInstance();

    }

    public static LoanCtr getInstance()
    { 
        //Creates a new instance if there is no instance running.
        if(loanCtr==null)
        {
            loanCtr = new LoanCtr();
        }
        return loanCtr;
    }

    public String createLoan(long _pid, String _serialNumber, long _loanID, String _borrowDate, String _period)
    {  
        //Creates a loan for a dvd.
        String str = "";
        if(addrCtr.isPerson(_pid) && dvdCtr.isDVDCopy(_serialNumber))
        {
            Loan l = new Loan(addrCtr.getPerson(_pid), dvdCtr.findDVDCopy(_serialNumber), _loanID, _borrowDate, _period);
            lList.addLoad(l);
            str+= " Loan no. " + _pid + " added.";
        }
        else
        {
            if(!addrCtr.isPerson(_pid))
            { 
                str += "\nError: Person not found.";
            }
            else
            if(!dvdCtr.isDVDCopy(_serialNumber))
            {
                str += "\nError: Serial Number is invalid.";
            }
        }
        return str;
    }
    
    public Loan findLoan(long _id)
    {
        //Searches for a loan.
        return lList.findLoan(_id);
    }
    
    public String printLoan(Loan _loan)
    {
        //Prints a list of information about a loan.
        String str;
        str ="ID: " + _loan.getID();
        str +="\nBorrow Date: " + _loan.getDate();
        str +="\nPeriod: " + _loan.getPeriod();
        str +="\nState: " + _loan.getState();
        return str;
    }
    
    public String listAllLoans()
    {   
        //Prints a list of all existing loans.
        String str = "Loans:\n";
        for (Loan ln : lList.getLoanList())
        {
            str += printLoan(ln);
        }
        return str;
    }
    
    public void returnCopy(String _serialNumber)
    {
        //Returns a copy of a dvd.
        long dvdID = dvdCtr.findDVDviaSerial(_serialNumber);
        Loan l = lList.findLoanViaCopy(dvdCtr.findDVDCopy(_serialNumber));
        l.setState("Returned.");
    }
      
}
